/*
 * Copyright (c) 2009, Magnus Robertsson. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package se.jayway.javafxbinder.model;

import java.beans.PropertyDescriptor;
import java.math.BigDecimal;

/**
 * Represents information about a JavaBean property.
 *
 * @author Magnus Robertsson
 */
public class PropertyInfo {
	private final PropertyDescriptor propertyDescriptor;

    public PropertyInfo(PropertyDescriptor propertyDescriptor) {
    	this.propertyDescriptor = propertyDescriptor;
	}

	public String getName() {
        return propertyDescriptor.getName();
    }

	public String getReadMethodName() {
		return propertyDescriptor.getReadMethod().getName();
	}

	public boolean isWritable() {
		return propertyDescriptor.getWriteMethod() != null;
	}
	
	public String getWriteMethodName() {
		return propertyDescriptor.getWriteMethod().getName();
	}
	
	public String getJavaFXTypeName() {
		Class<?> propertyType = propertyDescriptor.getPropertyType();
		if (propertyType.equals(String.class)) {
			return "String";
		} else if (propertyType.equals(Byte.TYPE)) {
			return "Integer";
		} else if (propertyType.equals(Short.TYPE)) {
			return "Integer";
		} else if (propertyType.equals(Integer.TYPE)) {
			return "Integer";
		} else if (propertyType.equals(Long.TYPE)) {
			return "Integer";
		} else if (propertyType.equals(Float.TYPE)) {
			return "Number";
		} else if (propertyType.equals(Double.TYPE)) {
			return "Number";
		} else if (propertyType.equals(Boolean.TYPE)) {
			return "Boolean";
		} else if (propertyType.equals(BigDecimal.class)) {
			return "Number";
		} else {
			return propertyType.getSimpleName();
		}
	}
	
	public String getJfxPropertyInitializer() {
		if (propertyDescriptor.getPropertyType().equals(BigDecimal.class)) {
			return "pojo."+getReadMethodName()+"().floatValue()";
		} else {
			return "pojo."+getReadMethodName()+"()";
		}
	}
	
	public String getJavaPropertySetterExpression() {
		if (propertyDescriptor.getPropertyType().equals(BigDecimal.class)) {
			return "new BigDecimal("+getName()+")";
		} else {
			return getName();
		}
	}
	
	public String getJfxPropertyFromEventExpression() {
		if (propertyDescriptor.getPropertyType().equals(BigDecimal.class)) {
			return "(event.getNewValue() as BigDecimal).floatValue()";
		} else {
			return "event.getNewValue() as "+getJavaFXTypeName();
		}
	}
}
